﻿using System;
using System.Collections.Generic;
using System.Text;
using Octopus.Logging.Commons;
using System.IO;

namespace Octopus.Logging.Impl.File
{
    public class FileWriter
    {
        private StringBuilder content = null;
        private TimeCaller caller = null;
        private bool isFulsh = false;
        private bool isChangeFile = true;

        public FileWriter(string fileName, int flushTime)
        {
            FileName = fileName;
            isFulsh = flushTime > 0;
            if (isFulsh)
            {
                content = new StringBuilder();
                caller = new TimeCaller();                
                caller.Start(flushTime, Flush);
            }
        }

        public bool Write(string value)
        {
            if (content.Length + value.Length > content.MaxCapacity)
            {
                Flush();
            }

            lock (this)
            {
                content.AppendLine(value);
                if (!isFulsh) { Flush(); }
            }

            return true;
        }

        private void Flush()
        {
            if (content.Length > 0)
            {
                lock (this) 
                {
                    if (isChangeFile)
                    {
                        CreateDirectory();
                        isChangeFile = false;
                    }

                    using (StreamWriter writer = new StreamWriter(FileName, true, Encoding.UTF8))
                    {
                        writer.Write(content.ToString());
                        content.Length = 0;
                    }
                }
            }
        }

        private void CreateDirectory()
        {
            string path = Path.GetDirectoryName(FileName);
            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
        }

        private string _FileName;
        public string FileName
        {
            get { return _FileName; }
            set 
            {
                if (value != _FileName)
                {
                    lock (this)
                    {
                        _FileName = value;
                        isChangeFile = true;
                    }
                }
            }
        }
    }
}
